import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { materialService } from '../../api/services/materialService';
import type {
  Material,
  CreateMaterialRequest,
  UpdateMaterialRequest,
  MaterialState
} from '../../api/types/material';

const initialState: MaterialState = {
  materials: [],
  loading: false,
  error: null,
};

export const fetchMaterials = createAsyncThunk(
  'material/fetchMaterials',
  async (_, { rejectWithValue }) => {
    try {
      return await materialService.getMaterials();
    } catch (error: any) {
      return rejectWithValue(error.message || '获取物资列表失败');
    }
  }
);

export const createMaterial = createAsyncThunk(
  'material/createMaterial',
  async (materialData: CreateMaterialRequest, { rejectWithValue }) => {
    try {
      return await materialService.createMaterial(materialData);
    } catch (error: any) {
      return rejectWithValue(error.message || '创建物资失败');
    }
  }
);

export const updateMaterial = createAsyncThunk(
  'material/updateMaterial',
  async ({ id, ...updateData }: { id: number } & UpdateMaterialRequest, { rejectWithValue }) => {
    try {
      return await materialService.updateMaterial(id, updateData);
    } catch (error: any) {
      return rejectWithValue(error.message || '更新物资失败');
    }
  }
);

export const deleteMaterial = createAsyncThunk(
  'material/deleteMaterial',
  async (materialId: number, { rejectWithValue }) => {
    try {
      await materialService.deleteMaterial(materialId);
      return materialId;
    } catch (error: any) {
       const errorMessage = error.response?.data?.error || error.message || '删除物资失败';
      return rejectWithValue(errorMessage);
    }
  }
);

const materialSlice = createSlice({
  name: 'material',
  initialState,
  reducers: {
    clearError: (state) => {
      state.error = null;
    },
    clearMaterials: (state) => {
      state.materials = [];
    },
    // 添加手动删除的reducer作为备选方案
    removeMaterialManual: (state, action) => {
      state.materials = state.materials.filter(m => m.id !== action.payload);
    }
  },
  extraReducers: (builder) => {
    builder
      // 获取物资列表
      .addCase(fetchMaterials.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchMaterials.fulfilled, (state, action) => {
        state.loading = false;
        state.materials = action.payload;
      })
      .addCase(fetchMaterials.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      })
      // 创建物资
      .addCase(createMaterial.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(createMaterial.fulfilled, (state, action) => {
        state.loading = false;
        state.materials.push(action.payload);
      })
      .addCase(createMaterial.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      })
      // 更新物资
      .addCase(updateMaterial.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(updateMaterial.fulfilled, (state, action) => {
        state.loading = false;
        const index = state.materials.findIndex(m => m.id === action.payload.id);
        if (index !== -1) {
          state.materials[index] = action.payload;
        }
      })
      .addCase(updateMaterial.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      })
      // 删除物资 - 重点修改这里
      .addCase(deleteMaterial.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(deleteMaterial.fulfilled, (state, action) => {
        state.loading = false;
        state.materials = state.materials.filter(m => m.id !== action.payload);
      })
      .addCase(deleteMaterial.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
       });
  },
});

export const { clearError, clearMaterials, removeMaterialManual } = materialSlice.actions;
export default materialSlice.reducer;